//
//  SNAllNotifyDataManager.m
//  app
//
//  Created by 王少宁 on 15/9/8.
//  Copyright (c) 2015年 hdaren. All rights reserved.
//

#import "SNAllNotifyDataManager.h"

@interface SNAllNotifyDataManager ()
@property (nonatomic, retain) JKHttpClient * http;
@property (nonatomic, retain) SNUniteUrl * uniteUrl;
@end

@implementation SNAllNotifyDataManager

+ (SNAllNotifyDataManager *)shareManager
{
    AS_SINGLETON(SNAllNotifyDataManager, manager, {
        manager = [[SNAllNotifyDataManager alloc] init];
        manager.http = [[JKHttpClient alloc] init];
        manager.uniteUrl = [SNUniteUrl shareUniteUrl];
    })
    return manager;
}

- (void)loadDataWithResult:(SNAllNotifyResult *)result page:(int)page
{
    if ([self.http isRunning]) {
        return;
    }
    
    result.failure = YES;
    result.success = result.noMoreData = NO;
    
    if (!page) {
        page = 0;
    }
    
    NSString * myAreaID = [[NSUserDefaults standardUserDefaults] objectForKey:kMyAreaID] && [[[NSUserDefaults standardUserDefaults] objectForKey:kMyAreaID] length] ? [[NSUserDefaults standardUserDefaults] objectForKey:kMyAreaID] : @"0";
    
    NSDictionary * params = @{@"cmid":myAreaID,
                              @"page":[NSString stringWithFormat:@"%d",page],
                              @"limit":[NSString stringWithFormat:@"%d",kLimit]};
    
    [self.http get:self.uniteUrl.sbgd_allNotifyUrl params:params result:^(JKResponse *resp) {
        if (resp.OK) {
            result.success = YES;
            result.failure = NO;
        
            if (resp.status == JKResponseTail) {
                result.noMoreData = YES;
            }
            
            NSArray * list = resp.content[@"list"];
            
            if (list.count) {
                
                if (list.count < kLimit) {
                    result.noMoreData = YES;
                }
                
                [self dataSourceArrayWithResult:result array:list page:page];
            }
            
        }
        
        [result invoke];
    }];
}

- (void)dataSourceArrayWithResult:(SNAllNotifyResult *)result array:(NSArray *)array page:(int)page
{
    if (page == 0 && result.dataSourceArray.count) {
        [result.dataSourceArray removeAllObjects];
    }
    
    for (NSDictionary * dic in array) {
        SNAllNotifyModel * model = [SNAllNotifyModel modelWithDict:dic];
        [result.dataSourceArray addObject:model];
    }
}

@end
